<template>
  <div class="search-bar">
    <a-space>
      <a-input-search v-model:value.trim="query.keywords" placeholder="输入菜单名称搜索" style="width: 300px"
        @search="handleSearch" />
      <a-button type="primary" @click="handleCreate" v-auth="101401">新增菜单</a-button>
    </a-space>
  </div>

  <a-table defaultExpandAllRows v-if="dataSource.length>0" :columns="columns" :data-source="dataSource" :pagination="pagination" @change="pagination.handleChange"
    row-key="id" bordered class="data-content">
    <template #bodyCell="{ column, record }">
      <!-- <template v-if="column.key === 'index'">
        {{ index + 1 }}
      </template> -->
      <template v-if="column.key === 'icon'">
        <span style="font-size: 32px;" class="ai-icon" :class="'ai-icon-' + record.icon"></span>
      </template>

      <template v-if="column.key === 'enabled'">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '启用' : '禁用' }}
        </a-tag>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space :size="8">
          <a-button v-auth="101403" type="link" size="small" @click="handleEditRole(record)">编辑</a-button>
          <a-popconfirm v-auth="101404" title="确定要删除这个菜单吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteRole(record)">
            <a-button type="link" size="small" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>

  <a-modal destroyOnClose :keyboard="false" :okButtonProps="{ loading: dialogEditor.loading }"
    v-model:open="dialogEditor.open" :title="dialogEditor.title" @ok="handleOk" @cancel="handleCancel" width="1200px">
    <menu-editor ref="editorRef" :id="dialogEditor.id" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import MenuEditor from './components/editor.vue';
import { MenuApi } from '@/api/services/index';
import { GetListInput, MenuDto } from '@/api/services/types';
import { ClientPagination, createPagedQuery, IDialogProps } from '@/api/abp';
import moment from 'moment';




// 模拟数据
const pagination = ref<ClientPagination>(new ClientPagination(() => {
  loadData();
}))
const dataSource = ref<Array<MenuDto>>([])
const query = reactive<GetListInput>({
  keywords: '',
  readOnly: true,
  sorting: 'creationTime desc,lastModificationTime desc',
  skipCount: 0,
  maxResultCount: 20
})
const dialogEditor = reactive<IDialogProps>({
  id: '',
  open: false,
  data: undefined,
  title: '',
  loading: false
})
const editorRef = ref<InstanceType<typeof MenuEditor>>();

const buildTree  = function(items:Array<MenuDto>,pid:string|null){
  const list:Array<MenuDto> = [];
  const children = items.filter(x=>x.parentId==pid);
  for (let index = 0; index < children.length; index++) {
    const child = children[index];
      const node = Object.assign({},child);
      if(items.filter(x=>x.parentId==child.id).length>0){
        node.children = buildTree(items,child.id);
      }
      list.push(node);
  }
  return list;
}

const loadData = function () {
  const input = createPagedQuery(pagination.value, query);
  MenuApi.getAll(input).then(res => {
    const { code, data, msg } = res;
    if (code == 0) {
      dataSource.value = buildTree(data.items || [],null);
      // pagination.value.total = data.totalCount;
      pagination.value.readOnly = true;
    } else {
      message.error(msg);
    }
  })
}

const handleSearch = function () {
  pagination.value.current = 1
  loadData();
}

const handleCreate = function () {
  dialogEditor.id = '';
  dialogEditor.title = '新增菜单';
  dialogEditor.open = true;
}

const handleEditRole = function (record: MenuDto) {
  dialogEditor.id = record.id;
  dialogEditor.title = '修改菜单';
  dialogEditor.open = true;
}

const handleDeleteRole = function (record: MenuDto) {
  MenuApi.delete(record.id).then(res => {
    const { code, msg } = res;
    if (code == 0) {
      message.success('删除成功');
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg);
    }
  })
}


const handleOk = async () => {
  dialogEditor.loading = true;
  editorRef.value?.submit().then(res => {
    const { code, msg } = res;
    if (code == 0) {
      dialogEditor.open = false;
      dialogEditor.id = '';
      message.success('保存成功')
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg);
    }
  }).finally(() => {
    dialogEditor.loading = false;
  })

};

const handleCancel = () => {
  dialogEditor.loading = false;
  dialogEditor.id = '';
  dialogEditor.open = false;

};




onMounted(() => {
  loadData();
})

const columns = [
  // {
  //   title: '序号',
  //   dataIndex: 'index',
  //   key: 'index',
  //   width: 70
  // },
  {
    title: '菜单名称',
    dataIndex: 'displayName',
    key: 'displayName',
    width:250
  },
  {
    title: '图标',
    dataIndex: 'icon',
    key: 'icon',
    width:100,
    align:'center'
  },
  {
    title: '地址',
    dataIndex: 'url',
    key: 'url'
  },
  {
        title: '权限码',
    dataIndex: 'permissions',
    key: 'permissions',
    customRender({value}){
      return (value||[]).map(x=>x.permissionCode).join(',');
    }
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks'
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    key: 'enabled',
    width:100
  },
  {
    title: '最后修改人',
    dataIndex: 'lastModifierName',
    key: 'lastModifierName',
    width: 150,
    customRender({ record }) {
      if (record.lastModifierName) {
        return record.lastModifierName;
      }
      return record.creatorName;
    }
  },
  {
    title: '最后修改时间',
    dataIndex: 'lastModificationTime',
    key: 'lastModificationTime',
    width: 160,
    customRender({ record }) {
      if (record.lastModificationTime) {
        return moment(record.lastModificationTime).format('YYYY-MM-DD HH:mm:ss');
      }
      return moment(record.creationTime).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
];

</script>

<style lang="scss" scoped>
.tenant-container {
  padding: 20px;
  background: #fff;
}

.search-bar {
  margin-bottom: 20px;
}

.data-content {
  flex: 1;

  .ant-table {
    flex: 1;
  }
}
</style>
